package com.thd.springboottest.shiro.sessionmanager;

import io.netty.util.internal.StringUtil;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * com.thd.springboottest.shiro.service.MySessionManager
 *
 * @author: wanglei62
 * @DATE: 2020/4/26 8:38
 **/
public class MySessionManager extends DefaultWebSessionManager {
    // 保存sessionId的请求头名称
    private static final String TOKEN = "token";

    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

    public MySessionManager() {
        super();
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        /**
         * 特别注意：
         * 如果重新定义了getSessionId，
         * 这个sessionId如果在服务端没有记录，则会重新生成一个sessionId，
         * 并放到header的setCookie中
         * 会造成每次请求都会新生成一个session
         *
         */

        // 取header中的token
        String id = WebUtils.toHttp(request).getHeader(TOKEN);
        // 如果header中没有token则从request中获取token参数
        if (StringUtils.isEmpty(id)){
            id = WebUtils.toHttp(request).getParameter(TOKEN);
        }

        //如果请求头中有 token 则其值为sessionId
        if (!StringUtils.isEmpty(id)) {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        } else {
            //否则按默认规则从cookie取sessionId
            return super.getSessionId(request, response);
        } 
    }
}
